package org.turbobytes.unikey.util.db.jdbc;


import org.turbobytes.unikey.util.db.DbException;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Template class like JdbcTemplate, but just lighter and has support for DbConnection ThreadLocal
 *
 * @author Ganeshji Marwaha
 * @since Aug 8, 2010
 */
public class DbTemplate {

  private DataSource dataSource;

  public DbTemplate(DataSource dataSource) {
    this.dataSource = dataSource;  
  }

  public <T> T execute(ConnectionCallback<T> closure) {
    Connection connection = null;
    try {
      connection = dataSource.getConnection();
      return closure.doInConnection(connection);
    } catch (SQLException e) {
      throw new DbException(e);
    } finally {
      try {
        if(connection != null) connection.close();
      } catch (SQLException e) {
        // Swallow - Known code pattern
      }
    }
  }

  
}
